package com.jiutong.meipenggang.ui.fragments;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.jiutong.meipenggang.R;
import com.jiutong.meipenggang.base.BaseFragment;
import com.jiutong.meipenggang.base.CommonAdapter;
import com.jiutong.meipenggang.base.ViewHolder;
import com.jiutong.meipenggang.entity.MeiLiCaiBean;
import com.jiutong.meipenggang.http.model.interfaces.BaseBiz;
import com.jiutong.meipenggang.http.model.requests.MeiLiCaiFragmentRequest;
import com.jiutong.meipenggang.http.present.MeiLiCaiInfoPresent;
import com.jiutong.meipenggang.http.subscribers.ProgressSubscriber;
import com.jiutong.meipenggang.http.subscribers.SubscriberOnNextListener;
import com.jiutong.meipenggang.ui.activitys.InvestDetailActivity;
import com.jiutong.meipenggang.utils.NumUilt;
import com.jiutong.meipenggang.utils.TimeUitl;
import com.jiutong.meipenggang.views.MyListView;
import com.jiutong.meipenggang.views.MyScrollView;
import com.jiutong.meipenggang.views.rollviewpager.AdvsPagerAdapter;
import com.jiutong.meipenggang.views.rollviewpager.ColorPointHintView;
import com.jiutong.meipenggang.views.rollviewpager.OnItemClickListener;
import com.jiutong.meipenggang.views.rollviewpager.RollPagerView;
import com.orhanobut.logger.Logger;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;


/**
 * Created by Veken on 2017/8/4.
 * 美理财投资
 */
public class InvestFragment extends BaseFragment implements BaseBiz {

    @Bind(R.id.iv_ads)
    RollPagerView ivAds;
    @Bind(R.id.lv_invest)
    MyListView lvInvest;
    @Bind(R.id.tv_meilicai_title)
    TextView tvMeiLiCaiTitle;
    @Bind(R.id.scroll_view)
    MyScrollView scrollView;
    @Bind(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    private MeiLiCaiInfoPresent meiLiCaiInfoPresent;
    private List<MeiLiCaiBean.BidListBean> bidList = new ArrayList<>();
    private List<MeiLiCaiBean.HomeAdsBean> homeAds = new ArrayList<>();
    private AdvsPagerAdapter advsPagerAdapter;
    private InvestAdapter investAdapter;

    private MeiLiCaiFragmentRequest meiLiCaiFragmentRequest;

    private int currentPage = 1;

    //轮播图的高度
    private int ivAdsHeight;

    private boolean mHidden;


    @Override
    protected int getLayoutResouceId() {
        return R.layout.fragment_invest;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mHidden) {
            return;
        }
        loadData();
        fresh();
    }

    /**
     * 下拉刷新，上拉加载
     */
    private void fresh() {
        //设置 Header 为 Material样式
        ClassicsHeader classicsHeader = new ClassicsHeader(mActivity);
        long currentTimeMillis = System.currentTimeMillis();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(currentTimeMillis);
        classicsHeader.setLastUpdateText("上次更新" + sdf.format(date));
        refreshLayout.setRefreshHeader(classicsHeader);
        //设置 Footer 为 经典样式
        refreshLayout.setRefreshFooter(new ClassicsFooter(mActivity));
        //刷新
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
                loadMore(1);
            }
        });
        //加载更多
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                refreshlayout.finishLoadmore(1000/*,false*/);//传入false表示加载失败
                loadMore(++currentPage);
            }
        });
        initListeners();
    }

    /**
     * 加载更多，请求网络
     */
    private void loadMore(int currentPage) {
        if (meiLiCaiFragmentRequest == null) {
            meiLiCaiFragmentRequest = new MeiLiCaiFragmentRequest();
        }
        SubscriberOnNextListener onNextListener = new SubscriberOnNextListener<MeiLiCaiBean>() {
            @Override
            public void onNext(MeiLiCaiBean object) {
                if (object.getError() == -1) {
                    showData(object);
                } else {
                    toastShortShow(object.getMsg());
                }
            }

            @Override
            public void onError(Throwable e) {
            }
        };
        HashMap<String, Object> fieldMap = new HashMap<>();
        fieldMap.put("OPT", 51);
        fieldMap.put("timestamp", TimeUitl.getDate());
        fieldMap.put("currPage", currentPage + "");
        meiLiCaiFragmentRequest.getMeiLiCaiFragmentInfo(new ProgressSubscriber(onNextListener, mActivity), fieldMap);
    }

    /**
     * 显示数据
     *
     * @param bean
     */
    private void showData(MeiLiCaiBean bean) {
        if (bean.getBidList().size() > 0) {
            for (int i = 0; i < bean.getBidList().size(); i++) {
                bidList.add(bean.getBidList().get(i));
            }
        } else {
            toastShortShow("没有数据");
        }
        investAdapter.notifyDataSetChanged();

    }

    /**
     * 获取顶部图片高度后，设置滚动监听
     */
    private void initListeners() {
        ViewTreeObserver vto = ivAds.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                tvMeiLiCaiTitle.getViewTreeObserver().removeGlobalOnLayoutListener(
                        this);
                ivAdsHeight = ivAds.getHeight();

                scrollView.setOnScrollChangeListener(new MyScrollView.OnScrollChangeListener() {
                    @Override
                    public void onScrollChanged(int l, int t, int oldl, int oldt) {
                        // TODO Auto-generated method stub
                        if (t <= 0) {   //设置标题的背景颜色
                            tvMeiLiCaiTitle.setBackgroundColor(Color.argb(0, 30, 144, 255));
                        } else if (t > 0 && t <= ivAdsHeight) { //滑动距离小于banner图的高度时，设置背景和字体颜色颜色透明度渐变
                            float scale = (float) t / ivAdsHeight;
                            float alpha = (255 * scale);
                            tvMeiLiCaiTitle.setTextColor(Color.argb((int) alpha, 255, 255, 255));
                            tvMeiLiCaiTitle.setBackgroundColor(Color.argb((int) alpha, 30, 144, 255));
                        } else {    //滑动到banner下面设置普通颜色
                            tvMeiLiCaiTitle.setBackgroundColor(Color.argb(255, 30, 144, 255));
                        }
                    }
                });
            }
        });
    }


    /**
     * 加载数据
     */
    private void loadData() {
        meiLiCaiInfoPresent = new MeiLiCaiInfoPresent(getContext(), this);
        meiLiCaiInfoPresent.getMeiLiCaiFragmentInfo();
    }


    @Override
    public void onSuccess(Object object) {
        MeiLiCaiBean bean = (MeiLiCaiBean) object;
        if (bean.getError() == -1) {
            homeAds = bean.getHomeAds();
            advsPagerAdapter = new AdvsPagerAdapter(getContext(), ivAds, homeAds);
            //设置透明度
            ivAds.setAnimationDurtion(500);
            //设置适配器
            ivAds.setAdapter(advsPagerAdapter);
            //设置指示器（顺序依次）
            //自定义指示器图片
            //设置圆点指示器颜色
            //设置文字指示器
            //隐藏指示器
            ivAds.setHintView(new ColorPointHintView(mActivity, Color.parseColor("#ffffff"), Color.parseColor("#50ffffff")));
            //banaer点击事件
            ivAds.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(int position) {

                }
            });
            bidList = bean.getBidList();
//            totalNum = bean.getTotalNum();
            investAdapter = new InvestAdapter(mActivity, bidList, R.layout.list_invest);
            lvInvest.setAdapter(investAdapter);
            lvInvest.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Bundle bundle = new Bundle();
                    bundle.putInt("bidId", bidList.get(position).getBidId());
                    openActivity(InvestDetailActivity.class, bundle);
                }
            });
        } else {
            Toast.makeText(getContext(), bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onError(Throwable e) {

    }

    @Override
    public int getOpt() {
        return 51;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        mHidden = hidden;
        if (!hidden) {
            loadData();
        }
    }

}

/**
 * 美理财投资列表适配器
 */
class InvestAdapter extends CommonAdapter<MeiLiCaiBean.BidListBean> {
    private ProgressBar itemProgressBar;
    private TextView tvItemProgress;
    private TextView tvItemInvestTime;
    private TextView tvItemInvestMoney;
    private TextView tvItemInvestRate;
    private TextView tvItemInvestStatus;
    private TextView tvItemInvestTitle;

    public InvestAdapter(Context context, List<MeiLiCaiBean.BidListBean> listDatas, int layoutId) {
        super(context, listDatas, layoutId);
    }

    @Override
    protected void fillData(ViewHolder holder, int position) {
        itemProgressBar = holder.getView(R.id.item_progressbar);
        tvItemProgress = holder.getView(R.id.tv_item_progress);
        tvItemInvestTime = holder.getView(R.id.tv_item_invest_time);
        tvItemInvestMoney = holder.getView(R.id.tv_item_invest_money);
        tvItemInvestRate = holder.getView(R.id.tv_item_invest_rate);
        tvItemInvestStatus = holder.getView(R.id.tv_item_invest_status);
        tvItemInvestTitle = holder.getView(R.id.tv_item_invest_title);
        //标的进度
        itemProgressBar.setProgress((int) Double.parseDouble(NumUilt.formatDouble(listDatas.get(position).getLoan_schedule())));
        //进度文本
        tvItemProgress.setText(listDatas.get(position).getLoan_schedule() + "%");
        //标的期限
        tvItemInvestTime.setText(listDatas.get(position).getPeriod() + "天");
        //标的金额
        tvItemInvestMoney.setText(NumUilt.doubleWanFormat(listDatas.get(position).getAmount() + ""));
        //标的利率
        tvItemInvestRate.setText(listDatas.get(position).getApr() + "");
        //标的title
        tvItemInvestTitle.setText(listDatas.get(position).getTitle() + "");
        switch (listDatas.get(position).getStatus()) {
            case 1:
            case 2:
                long time = Long.parseLong(listDatas.get(position).getBidding_time());
                long currentTime = System.currentTimeMillis();
                if (time <= currentTime) {
                    tvItemInvestStatus.setText("投标中");
                    tvItemInvestStatus.setBackgroundResource(R.mipmap.invest_item_blue);

                } else {
                    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
                    Date date = new Date();
                    date.setTime(time);
                    tvItemInvestStatus.setText(sdf.format(date) + "开始");
                }
                break;
            case 3:
                tvItemInvestStatus.setText("满标");
                tvItemInvestStatus.setBackgroundResource(R.mipmap.invest_item_gray);
                break;
            case 4:
            case 14:
                tvItemInvestStatus.setText("还款中");
                tvItemInvestStatus.setBackgroundResource(R.mipmap.invest_item_gray);
                break;
            case 5:
                tvItemInvestStatus.setText("投资结束");
                tvItemInvestStatus.setBackgroundResource(R.mipmap.invest_item_gray);
                break;
        }
    }
}

